#include "OcTree.h"
#include "Object.h"
#include "Grid.h"
#include "uivec3.h"

void mray::OcTree::Build(BaseObject** ppObjects, uint nObjects)
{
	BBox* boxArr = new BBox[nObjects];
	for(uint i = 0; i < nObjects; i++){
		boxArr[i] = ppObjects[i]->GetBBox();
		m_sceneBox &= boxArr[i];
	}
	vec3 diagonal = m_sceneBox.GetVector();
	vec3 center = (m_sceneBox.m_max + m_sceneBox.m_min)/2.f;
	float m_boxLen = diagonal[diagonal.GetMaxAxis()];
	m_sceneBox.m_min = center - vec3(m_boxLen, m_boxLen, m_boxLen);
	m_sceneBox.m_max = center + vec3(m_boxLen, m_boxLen, m_boxLen);

	for(uint i = 0; i < nObjects; i++)
		BuildNode(boxArr[i], ppObjects[i]);

}

void mray::OcTree::Build(Triangle** ppTriangles, uint nTriangles)
{

}

mray::OcTree::OcTree():
	m_root(nullptr), m_boxLen(0.f){}

void mray::OcTree::BuildNode(const BBox& box, BaseObject* pobject)
{
	uivec3 bounds[2];
	float cellLen;
	if(m_root == nullptr){
		m_root = new OcNode[8];
		cellLen = m_boxLen / std::pow(2.f, 1.f);
		bounds[0].Floor((box.m_min-m_sceneBox.m_min)/cellLen);
		bounds[1].Floor((box.m_max-m_sceneBox.m_min)/cellLen);

		for(uint z = bounds[0].z; z <= bounds[1].z; z++){
			for(uint y = bounds[0].y; y <= bounds[1].y; y++){
				for(uint x = bounds[0].x; x <= bounds[1].x; x++){

				}
			}
		}
	}
	//from level 0

}

mray::OcNode::OcNode():
	m_child(nullptr), m_pCell(nullptr){}

mray::OcNode::~OcNode()
{
	if(m_pCell) delete m_pCell;
	if(m_child)	delete [] m_child;
}
